package com.android.lovely.ui.fragment

import android.content.ClipData
import android.content.ClipboardManager
import android.content.Context
import android.view.ViewGroup
import android.widget.Toast
import androidx.core.view.isVisible
import androidx.fragment.app.activityViewModels
import androidx.lifecycle.lifecycleScope
import androidx.paging.filter
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout
import com.android.lovely.R
import com.android.lovely.const.CreatedImageRefresh
import com.android.lovely.const.HomeShowTask
import com.android.lovely.data.ImageGenerationTask
import com.android.lovely.databinding.FragmentWorkCreateRoleBinding
import com.android.lovely.databinding.ItemRoleTaskBinding
import com.android.lovely.ext.loadWithPlaceholder
import com.android.lovely.framework.BaseLoadAdapter
import com.android.lovely.framework.BaseLoadFragment
import com.android.lovely.framework.BaseLoadViewModel
import com.android.lovely.framework.UIController.showToast
import com.android.lovely.framework.widget.FlexibleContentContainer
import com.android.lovely.manager.KVStore
import com.android.lovely.ui.activity.AiGenerationActivity
import com.android.lovely.ui.activity.DownloadActivity
import com.android.lovely.ui.activity.OptimizationActivity
import com.android.lovely.ui.dialog.showLovelyDialog
import com.android.lovely.ui.viewmodel.WorkTaskViewModel
import com.kotlin.extensions.bus.FlowBus
import com.kotlin.extensions.bus.flowOf
import com.kotlin.extensions.context.ContextExt.startPage
import com.kotlin.extensions.coroutine.CoroutineExt.launchSafety
import com.kotlin.extensions.inflater.LayoutInflaterExt.layoutInflater
import com.kotlin.extensions.view.ViewExt.clickable
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.flow.combine
import kotlinx.coroutines.launch

/**
 *
 * @author why
 * @date 2025/4/8 16:03
 */
class WorkTaskFragment : BaseLoadFragment<FragmentWorkCreateRoleBinding, ImageGenerationTask>() {
    val viewModel by activityViewModels<WorkTaskViewModel>()

    var showTipClick = true

    override fun getViewModel(): BaseLoadViewModel<ImageGenerationTask> {
        return viewModel
    }

    override fun initView() {
        mBinding.flexState.update()
        mBinding.rv.layoutManager = LinearLayoutManager(requireContext())
        super.initView()

        val notice = getString(R.string.task_tip)
        mBinding.carousel.text = notice
        mBinding.llCarousel.isVisible =
            !(viewModel.status == 0 || viewModel.status == 1) && showTipClick
        mBinding.notifyClose.clickable {
            showTipClick = false
            mBinding.llCarousel.isVisible = false
        }


        lifecycleScope.launchSafety{
            viewModel.statueType.observe(viewLifecycleOwner){
                mBinding.llCarousel.isVisible =
                    !(viewModel.status == 0 || viewModel.status == 1) && showTipClick
                adapter.refresh()
            }
        }
        lifecycleScope.launchSafety{
            viewModel.pager.combine(viewModel.delete) { data, remove ->
                data.filter { it.id != remove }
            }.collectLatest {
                adapter.submitData(it)
            }
        }
        viewLifecycleOwner.lifecycleScope.launch {
            FlowBus.flowOf<HomeShowTask>().collect {
                adapter.refresh()
            }
        }
        viewLifecycleOwner.lifecycleScope.launch {
            FlowBus.flowOf<CreatedImageRefresh>().collect {
                adapter.refresh()
            }
        }
    }

    override fun getStateLayout(): FlexibleContentContainer {
        return mBinding.flexState
    }

    override fun getSwipeRefreshLayout(): SwipeRefreshLayout {
        return mBinding.srlRefresh
    }

    override fun getRecyclerView(): RecyclerView {
        return mBinding.rv
    }

    override fun getBaseAdapter(): BaseLoadAdapter<ImageGenerationTask, *> {
        val adapter = WorkTaskAdapter()
        adapter.listnener = object : WorkTaskAdapter.onItemTaskClick {
            override fun onItemClick(item: ImageGenerationTask, position: Int) {
                when (item.status) {
                    1 -> {
                        startPage<DownloadActivity>("task" to item)
                    }

                    0 -> Toast.makeText(
                        requireContext(), R.string.create_load_progress, Toast.LENGTH_SHORT
                    ).show()

                    else -> Toast.makeText(
                        requireContext(), R.string.create_load_failed, Toast.LENGTH_SHORT
                    ).show()
                }
            }

            override fun onItemDelete(item: ImageGenerationTask, position: Int) {
                requireActivity().showLovelyDialog {
                    setDialogMessage(getString(R.string.delete_ai_task))
                    setDialogTitle(getString(R.string.delete))
                    setPositiveButton {
                        viewModel.delete(item.id)
                    }
                }

            }

            override fun onEdit(item: ImageGenerationTask, position: Int) {
                startPage<AiGenerationActivity>("task" to item)
            }

            override fun onQuestion(item: ImageGenerationTask, p1: Int) {
                startPage<OptimizationActivity>("user_id" to item.id)
            }

        }
            return adapter
        }

        override suspend fun initData() {

        }

        class WorkTaskAdapter :
            BaseLoadAdapter<ImageGenerationTask, WorkRoleHolder>(
                object :
                    DiffUtil.ItemCallback<ImageGenerationTask>() {
                    override fun areItemsTheSame(
                        oldItem: ImageGenerationTask,
                        newItem: ImageGenerationTask
                    ): Boolean {
                        return false
                    }

                    override fun areContentsTheSame(
                        oldItem: ImageGenerationTask,
                        newItem: ImageGenerationTask
                    ): Boolean {
                        return false
                    }

                }
            ) {

            var listnener: onItemTaskClick? = null
            override fun onBindViewHolder(p0: WorkRoleHolder, p1: Int) {
                val item = getItem(p1) ?: return
                p0.binding.apply {
                    taskId.text =
                        root.context.getString(R.string.task_id, item.id.toString())

                    tvDesc.text =
                        root.context.getString(if (item.type == 0 || item.type == 2) R.string.task_text else R.string.task_img)
                    tvNum.text =
                        root.context.getString(R.string.task_number, item.count.toString())
                    iconAvatar.loadWithPlaceholder(item.imageUrl, R.drawable.icon_default_avatar)
                    ivStatus.setImageResource(
                        when (item.status) {
                            0 -> R.drawable.icon_role_task_load
                            1 -> R.drawable.icon_role_task_success
                            else -> R.drawable.icon_role_task_fail
                        }
                    )
                    taskId.clickable {
                        val clipboardManager =
                            root.context.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
                        val clipData = ClipData.newPlainText("label", item.id.toString())
                        clipboardManager.setPrimaryClip(clipData)
                        showToast(root.context.getString(R.string.copied_id))
                    }
                    root.clickable {
                        listnener?.onItemClick(item, p1)
                    }
                    ivEdit.clickable {
                        listnener?.onEdit(item, p1)
                    }
                    ivQustion.clickable {
                        listnener?.onQuestion(item, p1)
                    }
                    root.setOnLongClickListener {
                        listnener?.onItemDelete(item, p1)
                        true
                    }
                }
            }

            override fun onCreateViewHolder(p0: ViewGroup, p1: Int): WorkRoleHolder {
                return WorkRoleHolder(p0)
            }

            interface onItemTaskClick {
                fun onItemClick(item: ImageGenerationTask, position: Int)
                fun onItemDelete(item: ImageGenerationTask, position: Int)
                fun onEdit(item: ImageGenerationTask, position: Int)
                fun onQuestion(item: ImageGenerationTask, p1: Int)
            }

        }

        class WorkRoleHolder(
            parent: ViewGroup,
            val binding: ItemRoleTaskBinding = ItemRoleTaskBinding.inflate(
                parent.layoutInflater,
                parent,
                false
            )
        ) : RecyclerView.ViewHolder(binding.root)
    }